<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑相册' : '新建相册'"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      @submit.prevent
    >
      <el-form-item label="相册名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入相册名称" />
      </el-form-item>
      <el-form-item label="相册描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入相册描述"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import axios from "axios";

interface Props {
  visible: boolean;
  editData?: {
    id: number;
    name: string;
    description?: string;
  };
}

const props = defineProps<Props>();
const emit = defineEmits(["update:visible", "created", "updated"]);

const dialogVisible = ref(false);
const submitting = ref(false);
const formRef = ref<FormInstance>();

interface FormData {
  id: number;
  name: string;
  description: string;
}

const form = ref<FormData>({
  id: 0,
  name: "",
  description: "",
});

const rules: FormRules = {
  name: [
    { required: true, message: "请输入相册名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  description: [
    { max: 200, message: "描述不能超过200个字符", trigger: "blur" },
  ],
};

// 监听visible属性变化
watch(
  () => props.visible,
  (val) => {
    dialogVisible.value = val;
    if (val && props.editData) {
      form.value = {
        id: props.editData.id,
        name: props.editData.name,
        description: props.editData.description || "",
      };
    } else if (val) {
      form.value = {
        id: 0,
        name: "",
        description: "",
      };
    }
  }
);

// 监听对话框关闭
watch(
  () => dialogVisible.value,
  (val) => {
    if (!val) {
      emit("update:visible", false);
    }
  }
);

const isEdit = computed(() => !!props.editData);

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        const data = {
          name: form.value.name,
          description: form.value.description || "",
          userId: 1,
        };

        console.log("提交相册数据:", data);

        if (isEdit.value) {
          // 更新相册
          const response = await axios.put(
            `http://localhost:3000/albums/${form.value.id}`,
            data
          );
          console.log("相册更新响应:", response.data);
          ElMessage.success("相册更新成功");
          emit("updated", response.data);
        } else {
          // 创建相册
          const response = await axios.post(
            "http://localhost:3000/albums",
            data
          );
          console.log("相册创建响应:", response.data);
          ElMessage.success("相册创建成功");
          emit("created", response.data);
        }
        dialogVisible.value = false;
      } catch (error: any) {
        console.error(isEdit.value ? "更新相册失败:" : "创建相册失败:", error);
        const errorMessage =
          error.response?.data?.message ||
          error.response?.data?.error ||
          (isEdit.value ? "更新相册失败" : "创建相册失败");
        ElMessage.error(errorMessage);
      } finally {
        submitting.value = false;
      }
    }
  });
};

const handleCancel = () => {
  dialogVisible.value = false;
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
